<template>
  <div class="followup-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="客户">
          <el-select v-model="searchForm.customerId" placeholder="请选择客户" clearable filterable>
            <el-option
              v-for="customer in customerList"
              :key="customer.id"
              :label="customer.name"
              :value="customer.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="跟进中" :value="1" />
            <el-option label="已完成" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进人">
          <el-select v-model="searchForm.userId" placeholder="请选择跟进人" clearable filterable>
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.realName"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">总跟进记录</div>
            <div class="stats-value">{{ stats.totalCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">跟进中</div>
            <div class="stats-value">{{ stats.inProgressCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">已完成</div>
            <div class="stats-value">{{ stats.completedCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">本月新增</div>
            <div class="stats-value">{{ stats.monthlyNew || 0 }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-card class="action-card">
      <el-button type="primary" @click="handleAdd">新增跟进</el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedIds.length">
        批量删除
      </el-button>
      <el-button type="warning" @click="handleExport">导出Excel</el-button>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
    

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        border
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="customerName" label="客户名称" width="150" />
        <el-table-column prop="followupTime" label="跟进时间" width="140">
          <template #default="{ row }">
            {{ formatDate(row.followupTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="content" label="跟进内容" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'warning' : 'success'">
              {{ row.status === 1 ? '跟进中' : '已完成' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="跟进人" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="140">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="客户" prop="customerId">
          <el-select v-model="formData.customerId" placeholder="请选择客户" filterable>
            <el-option
              v-for="customer in customerList"
              :key="customer.id"
              :label="customer.name"
              :value="customer.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进时间" prop="followupTime">
          <el-date-picker
            v-model="formData.followupTime"
            type="datetime"
            placeholder="请选择跟进时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="跟进内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="4"
            placeholder="请输入跟进内容"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="跟进中" :value="1" />
            <el-option label="已完成" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进人" prop="userId">
          <el-select v-model="formData.userId" placeholder="请选择跟进人" filterable>
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.realName"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="跟进详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="客户名称">{{ viewData.customerName }}</el-descriptions-item>
        <el-descriptions-item label="跟进时间">{{ formatDate(viewData.followupTime) }}</el-descriptions-item>
        <el-descriptions-item label="跟进内容" :span="2">{{ viewData.content }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="viewData.status === 1 ? 'warning' : 'success'">
            {{ viewData.status === 1 ? '跟进中' : '已完成' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="跟进人">{{ viewData.userName }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ formatDate(viewData.createTime) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { followupApi } from '@/api/crm/followup'
import { customerApi } from '@/api/crm/customer'
import { UserListJS } from '@/api/sys/user_sys'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedIds = ref([])
const customerList = ref([])
const userList = ref([])
const stats = reactive({
  totalCount: 0,
  inProgressCount: 0,
  completedCount: 0,
  monthlyNew: 0
})

// 搜索表单
const searchForm = reactive({
  customerId: null,
  status: null,
  userId: null
})

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogTitle = ref('新增跟进')
const formRef = ref()
const formData = reactive({
  id: '',
  customerId: null,
  followupTime: '',
  content: '',
  status: 1,
  userId: null
})
const viewData = reactive({})

// 表单验证规则
const formRules = {
  customerId: [
    { required: true, message: '请选择客户', trigger: 'change' },
    { validator: (rule, value, callback) => {
      if (!value || value === '') {
        callback(new Error('请选择客户'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入跟进内容', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (!value || value.trim() === '') {
        callback(new Error('跟进内容不能为空'))
      } else if (value.trim().length < 2) {
        callback(new Error('跟进内容至少2个字符'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ],
  userId: [
    { required: true, message: '请选择跟进人', trigger: 'change' },
    { validator: (rule, value, callback) => {
      if (!value || value === '') {
        callback(new Error('请选择跟进人'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ]
}

// 获取数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    
    const response = await followupApi.list(params)
    
    if (response && response.code === 200 && response.data) {
      const page = response.data
      tableData.value = page?.records || []
      pagination.total = page?.total || 0
    } else {
      console.error('API返回错误:', response)
      ElMessage.error('获取数据失败：数据格式不正确')
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取跟进数据失败:', error)
    ElMessage.error('获取数据失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const loadStats = async () => {
  try {
    const response = await followupApi.getStats()
    
    if (response && response.code === 200 && response.data) {
      const data = response.data
      Object.assign(stats, data)
    } else {
      console.error('统计数据响应格式错误:', response)
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取客户列表
const loadCustomerList = async () => {
  try {
    const response = await customerApi.list()
    if (response && response.code === 200 && response.data) {
      customerList.value = response.data.records || []
    } else {
      console.error('获取客户列表失败:', response)
      customerList.value = []
    }
  } catch (error) {
    console.error('获取客户列表失败:', error)
    customerList.value = []
  }
}

// 获取用户列表
const loadUserList = async () => {
  try {
    const response = await UserListJS({ current: 1, size: 1000 })
    if (response && response.code === 200 && response.data) {
      userList.value = response.data.records || []
    } else {
      console.error('获取用户列表失败:', response)
      userList.value = []
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    userList.value = []
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
  loadStats()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    customerId: null,
    status: null,
    userId: null
  })
  pagination.current = 1
  loadData()
  loadStats()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增
const handleAdd = () => {
  console.log('新增跟进记录')
  dialogTitle.value = '新增跟进'
  
  // 清空表单数据
  Object.assign(formData, {
    id: '',
    customerId: null,
    followupTime: '',
    content: '',
    status: 1,
    userId: null
  })
  
  console.log('表单数据已重置:', formData)
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  Object.assign(viewData, row)
  viewDialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  console.log('编辑跟进记录:', row)
  dialogTitle.value = '编辑跟进'
  
  // 清空表单数据，然后重新赋值
  Object.assign(formData, {
    id: '',
    customerId: null,
    followupTime: '',
    content: '',
    status: 1,
    userId: null
  })
  
  // 将行数据赋值给表单
  Object.assign(formData, row)
  console.log('表单数据已更新:', formData)
  
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    console.log('删除跟进记录:', row)
    await ElMessageBox.confirm('确定要删除这条跟进记录吗？', '提示', {
      type: 'warning'
    })
    
    const response = await followupApi.delete(row.id)
    console.log('删除API响应:', response)
    
    if (response && response.code === 200) {
      ElMessage.success('删除成功')
      loadData()
      loadStats()
    } else {
      ElMessage.error(response?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除跟进记录失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要删除的跟进记录')
    return
  }
  
  try {
    console.log('批量删除跟进记录:', selectedIds.value)
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 条跟进记录吗？`, '提示', {
      type: 'warning'
    })
    
    const response = await followupApi.batchDelete(selectedIds.value)
    console.log('批量删除API响应:', response)
    
    if (response && response.code === 200) {
      ElMessage.success('批量删除成功')
      loadData()
      loadStats()
    } else {
      ElMessage.error(response?.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除跟进记录失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    console.log('提交表单数据:', formData)
    await formRef.value.validate()

    // 准备提交数据，确保数据类型正确
    const submitData = {
      customerId: formData.customerId ? Number(formData.customerId) : null,
      userId: formData.userId ? Number(formData.userId) : null,
      status: formData.status ? Number(formData.status) : 1,
      content: formData.content ? String(formData.content).trim() : ''
    }

    // 跟进时间：如果选择了，则转为ISO字符串；否则不传，让后端自动填充
    if (formData.followupTime && String(formData.followupTime).trim() !== '') {
      const dt = new Date(formData.followupTime)
      if (!isNaN(dt.getTime())) {
        submitData.followupTime = dt.toISOString()
      }
    }

    // 验证必填字段
    if (!submitData.customerId) {
      ElMessage.error('请选择客户')
      return
    }
    if (!submitData.content || submitData.content.trim() === '') {
      ElMessage.error('请输入跟进内容')
      return
    }
    if (!submitData.userId) {
      ElMessage.error('请选择跟进人')
      return
    }

    console.log('提交的数据:', submitData)

    let response
    if (formData.id) {
      // 更新时携带ID
      response = await followupApi.update({ id: formData.id, ...submitData })
    } else {
      response = await followupApi.add(submitData)
    }

    console.log('API响应:', response)

    if (response && response.code === 200) {
      ElMessage.success(formData.id ? '更新成功' : '新增成功')
      dialogVisible.value = false
      loadData()
      loadStats()
    } else {
      ElMessage.error(response?.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败')
  }
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 导出
const handleExport = async () => {
  try {
    if (!tableData.value || tableData.value.length === 0) {
      ElMessage.warning('暂无数据可导出，请先加载数据')
      return
    }
    
    ElMessage.info('正在导出跟进数据，请稍候...')
    
    // 准备CSV数据
    const headers = ['客户名称', '跟进时间', '跟进内容', '状态', '跟进人', '创建时间']
    const dataList = []
    
    // 添加数据行
    tableData.value.forEach(row => {
      dataList.push([
        row.customerName || '',
        formatDate(row.followupTime),
        row.content || '',
        row.status === 1 ? '跟进中' : '已完成',
        row.userName || '',
        formatDate(row.createTime)
      ])
    })
    
    // 添加汇总行
    dataList.push([
      '总计',
      '',
      '',
      '',
      '',
      `记录数: ${pagination.total || 0}`
    ])
    
    // 创建CSV文件并下载
    const workbook = new Blob([
      '\uFEFF' + // BOM for UTF-8
      headers.join(',') + '\n' +
      dataList.map(row => row.join(',')).join('\n')
    ], { type: 'text/csv;charset=utf-8;' })
    
    const url = window.URL.createObjectURL(workbook)
    const link = document.createElement('a')
    link.href = url
    link.download = `客户跟进记录_${new Date().toISOString().slice(0, 10)}.csv`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败：' + error.message)
  }
}

// 工具函数
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  if (isNaN(d)) return String(date).slice(0, 10)
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

// 初始化
onMounted(() => {
  loadData()
  loadStats()
  loadCustomerList()
  loadUserList()
})
</script>

<style scoped>
.followup-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.stats-item {
  padding: 10px;
}

.stats-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.action-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
